<?php

namespace SLN0002\DAO;

use Home\DAO\PSIBaseExDAO;

/**
 * 一些共同功能
 *
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
class AccCommDAO extends PSIBaseExDAO
{
  /**
   * 查询某个公司的当前会计期间
   * 
   * @return 如果返回null表示当前公司没有建账
   */
  public function getCurrentAccYearAndMonth($companyId)
  {
    $db = $this->db;

    $sql = "select acc_year, acc_month
            from t_acc_current_period
            where company_id = '%s' ";
    $data = $db->query($sql, $companyId);
    if (!$data) {
      return null;
    }

    $v = $data[0];
    return [
      "accYear" => $v["acc_year"],
      "accMonth" => $v["acc_month"],
    ];
  }

  /**
   * 构建会计期间的字符串表示
   */
  public function buildPeriodStr($accYear, $accMonth)
  {
    $p = "";
    if ($accMonth < 10) {
      $p = "{$accYear}-0{$accMonth}";
    } else {
      $p = "{$accYear}-{$accMonth}";
    }

    return $p;
  }

  /**
   * 月末日期
   */
  public function buildVoucherLastDT($accYear, $accMonth)
  {
    // 先取下个月的第一天，然后减去一天，算出当前会计期间的最后一天（避免闰月之类的麻烦事）

    $dt = "";
    $y = $accYear;
    $m = $accMonth + 1;
    if ($m == 13) {
      $y = $y + 1;
      $dt = "$y-01-01";
    } else {
      if ($m < 10) {
        $dt = "{$y}-0{$m}-01";
      } else {
        $dt = "{$y}-{$m}-01";
      }
    }
    $d = date_create($dt);
    date_sub($d, date_interval_create_from_date_string("1 day"));
    $voucherDT = date_format($d, "Y-m-d");

    return $voucherDT;
  }

  /**
   * 查询科目的余额方向
   * 
   * 返回值：借方、贷方、借贷均可
   */
  public function querySubjectDir($companyId, $subjectCode)
  {
    $db = $this->db;

    $sql = "select balance_dir
            from t_subject
            where code = '%s' and company_id = '%s' ";
    $data = $db->query($sql, $subjectCode, $companyId);
    if (!$data) {
      // 莫名的bug
      return null;
    }

    $dir = $data[0]["balance_dir"];
    switch ($dir) {
      case 0:
        return "借贷均可";
      case 1:
        return "借方";
      case 2:
        return "贷方";
      default:
        // 莫名的bug
        return null;
    }
  }
}
